package ua.kiev.tosik.price.gui;

import org.apache.commons.lang.time.DurationFormatUtils;
import org.apache.log4j.Logger;
import ua.kiev.tosik.price.IChapter;
import ua.kiev.tosik.price.conf.Chapter;

public class ChapterRunner {

	private static Logger logger = Logger.getLogger("ua.kiev.tosik.price.gui");

	@SuppressWarnings("unchecked")
	public static void runChapter(Chapter chapter) {
		long startTime = System.currentTimeMillis();
		logger.debug("Try to run Chapter: " + chapter.getName() + " [" + chapter.getClassName() + "]");
		try {
			Class clazz = Class.forName(chapter.getClassName());
			logger.debug("Class name: " + clazz.getName());
			IChapter ch = (IChapter)clazz.getConstructor().newInstance();
			if ( CenterPanel.getInstance().countOpenedTabByTitle(ch.getTitle()) == 0 || chapter.isMultiple() ) {
				ch.init();
				CenterPanel.getInstance().addTab(ch, chapter.getImageSmall());
			} else {
				logger.debug("Chapter already in workspace");
			}
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e);
		}
		logger.debug("Chapter running duration: " + DurationFormatUtils.formatDuration((System.currentTimeMillis()-startTime), "s.S") + " sec");
	}

}
